#include "utilities.h"
#include <QString>

Utilities::Utilities(QObject *parent) : QObject(parent) {}

/* 取数值的某一位*/
QString Utilities::GetBit(int x, int y)
{
    return QString:: number((x) >> (y) & 1);
}

/* 校验和 */
//数组和
uint8_t Utilities::check_sum(uint8_t *buf,int leng)
{
    uint8_t sum=0;
    for (int i = 0; i < leng-2; i++ )
    {
        sum += buf[i];
    }
    sum &= 0xFF;
    return sum;
}

void Utilities::String2Hex(QString str,QByteArray &buf)
{
    int HData,LData;
    int hexlen = 1 ,len = str.length();
    char Hstr, Lstr;
//    qDebug() << "len"<<len;
    if(len > 1){
        Hstr = str[0].toLatin1();
        Lstr = str[1].toLatin1();
//        qDebug() << "what" << Hstr;
//        qDebug() << "what" << Lstr;
        HData = Char2Hex(Hstr);
        LData = Char2Hex(Lstr);
//        qDebug() << "what" << HData;
//        qDebug() << "what" << LData;
//        buf[0] = (char) HData*16 +LData;
        buf[0] = static_cast<char>(HData*16 +LData);
    }
    else
    {
        Hstr = str[0].toLatin1();
        HData = Char2Hex(Hstr);
        buf[0] = static_cast<char>(HData);
    }
    buf.resize(hexlen);
}

char Utilities::Char2Hex(char ch)
{
    if(ch >= '0' && ch <= '9')
        return ch - 0x30;
    else if(ch >='A' && ch <='F')
        return ch - 'A' + 10;
    else if(ch >='a' && ch <= 'f')
        return ch - 'a' + 10;

    else return -1;
}
